﻿using UFSoft.UBF.Eventing;


namespace ufida.u9.cust.dz.beplugin.TransferIn
{
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using ufida.u9.cust.dz.beplugin.JkySchema;
    using ufida.u9.cust.dz.beplugin.loger;
    using ufida.u9.cust.dz.beplugin.Utils;
    using UFIDA.U9.Base;
    using UFIDA.U9.InvDoc.TransferIn;
    using UFSoft.UBF.Util.Context;

    class AfterUpdated : IEventSubscriber
    {
        public void Notify(params object[] args)
        {

            if (PlatformContext.Current.EnterpriseID.Equals("10"))
            {

                TransferIn entity = null;
                if (BaseCommon.TryGetEntity(args, ref entity))
                {
                    //单据类型


                    TransInStatus Current = entity.Status;
                    TransInStatus Original = entity.OriginalData.Status;

                    string InWh = entity.TransInLines[0].TransInWh.DescFlexField.PrivateDescSeg1;
                    string OutWh = entity.TransInLines[0].TransInSubLines[0].TransOutWh.DescFlexField.PrivateDescSeg1;

                    string InWh2 = entity.TransInLines[0].TransInWh.DescFlexField.PrivateDescSeg2;
                    string OutWh2 = entity.TransInLines[0].TransInSubLines[0].TransOutWh.DescFlexField.PrivateDescSeg2;

                    if (Original == TransInStatus.Approving && Current == TransInStatus.Approved && !entity.DocType.Code.Equals("TransIn009"))
                    {
                        if (InWh.Equals("True") || InWh2.Equals("True"))
                        {

                            // 电商仓到电商仓
                            if (OutWh.Equals("True") || OutWh2.Equals("True"))
                            {
                                EShopHead obj = TurnEShopParams(entity);
                                string jsonObj = JsonConvert.SerializeObject(obj);
                                WebResult res = Task.Run(() => JkyUtils.Post("erp.allocate.quick.create", jsonObj)).GetAwaiter().GetResult();
                                LogUtil logUtil = new LogUtil();
                                if (res.Sucess)
                                {
                                    JkyResponse jkyResponse = JsonConvert.DeserializeObject<JkyResponse>(res.Data);
                                    if (!jkyResponse.code.Equals("200"))
                                    {
                                        logUtil.RecordLog(entity.DocNo, "电商传电商", obj, 0, jkyResponse.msg);
                                        throw new Exception("推送吉克云失败:" + jkyResponse.msg);
                                    }
                                    else
                                    {
                                        logUtil.RecordLog(entity.DocNo, "电商传电商", obj, 1, "推送成功");
                                    }
                                }
                                else
                                {
                                    logUtil.RecordLog(entity.DocNo, "电商传电商", obj, 0, JsonUtils.Serialize(res));
                                    throw new Exception("推送失败");
                                }
                            }
                            else
                            {
                                //仓库转储 非电商仓到电商仓
                                JkyHead obj = TurnJkyParams(entity);
                                string jsonObj = JsonConvert.SerializeObject(obj);
                                WebResult res = Task.Run(() => JkyUtils.Post("erp.stock.createandstockin", jsonObj)).GetAwaiter().GetResult();
                                LogUtil logUtil = new LogUtil();
                                if (res.Sucess)
                                {

                                    JkyResponse jkyResponse = JsonConvert.DeserializeObject<JkyResponse>(res.Data);

                                    if (!jkyResponse.code.Equals("200"))
                                    {
                                        logUtil.RecordLog(entity.DocNo, "非电商传电商", obj, 0, jkyResponse.msg);
                                        throw new Exception("推送吉克云失败:" + jkyResponse.msg);
                                    }
                                    else
                                    {
                                        logUtil.RecordLog(entity.DocNo, "非电商传电商", obj, 1, "推送成功");
                                    }

                                }
                                else
                                {
                                    logUtil.RecordLog(entity.DocNo, "非电商传电商", obj, 0, JsonUtils.Serialize(res));

                                    throw new Exception("推送失败");
                                }
                            }
                        }
                    }

                }
            }

        }

        private JkyHead TurnJkyParams(TransferIn entity)
        {
            JkyHead jkyHead = new JkyHead();

            jkyHead.inType = "104";
            jkyHead.relDataId = entity.DocNo;
            jkyHead.applyDepartCode = entity.TransInLines[0].TransInWhMan == null ? "" : entity.TransInLines[0].TransInWhMan.Dept.Code + '-' + entity.TransInLines[0].Org.Code;
            jkyHead.applyCompanyCode = "00" + entity.TransInLines[0].Org.Code;
            jkyHead.inWarehouseCode = entity.TransInLines[0].TransInWh.Code;
            jkyHead.applyDate = entity.BusinessDate.ToString("yyyy-MM-dd HH:mm:ss");
            jkyHead.auditDate = entity.BusinessDate.ToString("yyyy-MM-dd HH:mm:ss");
            jkyHead.planInDate = entity.BusinessDate.ToString("yyyy-MM-dd HH:mm:ss");
            jkyHead.applyUserName = entity.TransInLines[0].TransInWhMan == null ? "" : entity.TransInLines[0].TransInWhMan.Name;
            //jkyHead.applyDepartCode = entity.TransInLines[0].TransInWhMan == null ? "" : entity.TransInLines[0].TransInWhMan.Dept.Code;
            jkyHead.@operator = Context.LoginUser;

            jkyHead.stockInDetailViews = new List<JkyLine>();

            foreach (var line in entity.TransInLines)
            {
                JkyLine jkyLine = new JkyLine();

                jkyLine.outSkuCode = line.ItemInfo.ItemCode;
                jkyLine.skuCount = line.StoreUOMQty;
                jkyLine.relDetailId = line.ID.ToString();

                //批号
                if (line.LotInfo != null && line.LotInfo.LotMaster != null)
                {
                    jkyLine.batchList = new List<Batch>() { new Batch() { batchNo = line.LotInfo.LotCode, quantity = line.StoreUOMQty, productionDate = line.LotInfo.LotMaster.EffectiveDatetime.ToString("yyyy-MM-dd HH:mm:ss") } };
                }
                //序列号 一个料品对应一个序列号对象
                //jkyLine.serialList = new List<JkySerial>();
                //for (int i = 1; i <= line.StoreUOMQty; i++)
                //{
                //    //获取时间戳
                //    long milliseconds = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                //    jkyLine.serialList.Add(new JkySerial() { serialNo = line.ItemInfo.ItemCode + "-" + milliseconds.ToString() + "-" + i });
                //}
                jkyHead.stockInDetailViews.Add(jkyLine);
            }
            return jkyHead;
        }


        private EShopHead TurnEShopParams(TransferIn entity)
        {
            EShopHead eShopHead = new EShopHead();
            eShopHead.applyUserName = entity.TransInLines[0].TransInWhMan == null ? "" : entity.TransInLines[0].TransInWhMan.Name;
            eShopHead.departCode = entity.TransInLines[0].TransInWhMan == null ? "" : entity.TransInLines[0].TransInWhMan.Dept.Code + '-' + entity.TransInLines[0].Org.Code;
            eShopHead.applyDepartName = entity.TransInLines[0].TransInWhMan == null ? "" : entity.TransInLines[0].TransInWhMan.Dept.Name;
            eShopHead.applyDate = entity.BusinessDate.ToString("yyyy-MM-dd HH:mm:ss");
            eShopHead.gmtCreate = entity.BusinessDate.ToString("yyyy-MM-dd HH:mm:ss");
            eShopHead.auditDate = entity.BusinessDate.ToString("yyyy-MM-dd HH:mm:ss");
            eShopHead.planOutDate = entity.BusinessDate.ToString("yyyy-MM-dd HH:mm:ss");
            eShopHead.planInDate = entity.BusinessDate.ToString("yyyy-MM-dd HH:mm:ss");

            eShopHead.companyCode = "00" + entity.TransInLines[0].Org.Code;
            eShopHead.currencyRate = 1;
            eShopHead.outCurrencyCode = "CNY";
            eShopHead.inCurrencyCode = "CNY";
            eShopHead.outWarehouseCode = entity.TransInLines[0].TransInSubLines[0].TransOutWh.Code;
            eShopHead.intWarehouseCode = entity.TransInLines[0].TransInWh.Code;
            eShopHead.sourceNo = entity.DocNo;
            eShopHead.applyUserId = entity.TransInLines[0].TransInWhMan == null ? 1 : entity.TransInLines[0].TransInWhMan.ID;

            eShopHead.stockAllocateDetailViews = new List<EShopLine>();
            foreach (var line in entity.TransInLines)
            {
                EShopLine eShopLine = new EShopLine();
                eShopLine.unitName = line.StoreUOM.Name;
                eShopLine.skuCount = line.StoreUOMQty;
                eShopLine.skuPrice = line.PriceIncludeTax;
                eShopLine.outSkuCode = line.ItemInfo.ItemCode;
                eShopHead.stockAllocateDetailViews.Add(eShopLine);
            }

            return eShopHead;
        }
    }

}
